﻿using Infrastructure;
using Infrastructure.Attribute;
using ZR.Service;
using ZR.ServiceCore.Model;
using ZR.ServiceCore.Services.IService;

namespace ZR.ServiceCore.Services;

[AppService(ServiceType = typeof(IRateLimitRuleService), ServiceLifetime = LifeTime.Transient)]
public class RateLimitRuleService : BaseService<RateLimitRule>, IRateLimitRuleService
{
    public async Task<List<RateLimitRule>> DeleteRateLimitRuleAsync(long id)
    {
        var isExist = await Queryable()
            .Where(it => it.Id == id)
            .SingleAsync();
        if (isExist == null)
        {
            throw new CustomException("数据不存在，无法删除");
        }
        var del = await Deleteable()
            .Where(it => it.Id == id)
            .ExecuteCommandAsync();
        if (del <= 0) throw new CustomException("删除失败");
        {
            var res = await Queryable()
                .Where(it => it.IpRateLimitPolicyId == isExist.IpRateLimitPolicyId)
                .ToListAsync();
            return res;
        }
    }

    public async Task<char> ChangeRateLimitRuleFlagAsync(long id)
    {
        var isExist = await Queryable()
            .Where(it => it.Id == id)
            .SingleAsync();
        if (isExist == null) throw new CustomException("数据不存在，无法更改");
        var upd = await Updateable(new RateLimitRule
            {
                Id = id,
                Flag = isExist.Flag == '1' ? '0' : '1'
            }).UpdateColumns(it => it.Flag)
            .ExecuteCommandAsync();
        if (upd == 0) throw new CustomException("更改失败");
        {
            var res = isExist.Flag == '1' ? '0' : '1';
            return res;
        }
    }
}
